/* eslint-disable prefer-const */
/**
 * @author Mr.fan
 * @description 快速在pages文件夹下某个位置创建常用文件和文件夹
 * @description 命令  yarn create-dir (pages下的相对路径) 文件夹名称
 */

const fs = require('fs');
const path = require('path');

const dirPath = process.argv[2]; // 获取创建文件夹的位置
const dirName = process.argv[3]; // 获取创建文件夹的名称

const arr_path = [__dirname, dirPath, dirName];

// 页面初始化内容
const content = `
import { PageContainer } from "@ant-design/pro-layout"

import styles from "./index.less"

export default (props:any)=>{
    return (
       <PageContainer header={{title: undefined,}}>
         <div className={styles.${dirName}}>${dirName}</div>
       </PageContainer>
     );
}
`;
// 页面组件导入方式
const com_content = `
import './index.less'

export {}
`;

// 创建文件夹和文件
const create = async () => {
  fs.writeFile(path.join(...arr_path, 'index.less'), '//', () => {
    return true;
  });
  fs.writeFile(path.join(...arr_path, 'index.tsx'), content, () => {
    return true;
  });
  fs.mkdirSync(path.join(...arr_path, 'component'));
  fs.writeFile(path.join(...arr_path, 'component', 'index.less'), '//', () => {
    return true;
  });
  fs.writeFile(path.join(...arr_path, 'component', 'index.ts'), com_content, () => {
    return true;
  });
  console.log('创建成功');
};

if (dirPath.startsWith('/') && dirName) {
  try {
    const stat = fs.statSync(path.join(...arr_path));
    if (stat) console.log('文件已经存在，请重新输入');
  } catch (error) {
    // 同步创建文件夹
    fs.mkdirSync(path.join(...arr_path));
    try {
      const stat = fs.statSync(path.join(...arr_path));
      if (stat) create();
    } catch (errors) {
      console.log('创建失败');
    }
  }
} else {
  throw new SyntaxError('dirPath or dirName not exist');
}
